import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, Tabs, message } from 'antd';
import { UserOutlined, LockOutlined, MobileOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import { useVerify } from '../../contexts/VerifyContext';
import './Login.scss';

interface LoginForm {
  username: string;
  password: string;
  remember: boolean;
}

interface PhoneLoginForm {
  phone: string;
  code: string;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const { showVerify } = useVerify();
  const [form] = Form.useForm<LoginForm>();
  const [phoneForm] = Form.useForm<PhoneLoginForm>();
  const [loading, setLoading] = useState(false);
  const [loginType, setLoginType] = useState<'account' | 'phone'>('account');
  const [countdown, setCountdown] = useState(0);

  // 账号密码登录
  const handleAccountLogin = async (values: LoginForm) => {
    // 先进行图形验证
    setLoading(true);
    const isVerified = await showVerify({
      title: '登录验证',
      description: '请输入图片中的验证码',
    });

    if (!isVerified) {
      setLoading(false);
      message.warning('验证失败，请重试');
      return;
    }

    try {
      // TODO: 调用登录接口
      // const response = await login(values);
      
      // 模拟登录
      setTimeout(() => {
        localStorage.setItem('token', 'mock_token_' + Date.now());
        localStorage.setItem('userInfo', JSON.stringify({
          id: '1',
          username: values.username,
          email: 'user@example.com',
          avatar: 'https://picsum.photos/100/100',
          role: 'student'
        }));
        
        message.success('登录成功！');
        navigate('/');
      }, 1000);
    } catch (error) {
      message.error('登录失败，请检查账号密码');
    } finally {
      setLoading(false);
    }
  };

  // 手机号登录
  const handlePhoneLogin = async (values: PhoneLoginForm) => {
    setLoading(true);
    try {
      // TODO: 调用手机号登录接口
      message.success('登录成功！');
      navigate('/');
    } catch (error) {
      message.error('登录失败');
    } finally {
      setLoading(false);
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    const phone = phoneForm.getFieldValue('phone');
    if (!phone) {
      message.error('请输入手机号');
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      message.error('请输入正确的手机号');
      return;
    }

    // TODO: 调用发送验证码接口
    message.success('验证码已发送');
    
    // 倒计时
    let count = 60;
    setCountdown(count);
    const timer = setInterval(() => {
      count--;
      setCountdown(count);
      if (count === 0) {
        clearInterval(timer);
      }
    }, 1000);
  };

  const tabItems = [
    {
      key: 'account',
      label: '账号登录',
      children: (
        <Form
          form={form}
          name="account-login"
          onFinish={handleAccountLogin}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入账号' },
              { min: 3, message: '账号至少3个字符' }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入账号/邮箱"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6个字符' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
            />
          </Form.Item>

          <Form.Item>
            <div className="login-options">
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我（7天）</Checkbox>
              </Form.Item>
              <Link to="/forgot-password" className="forgot-link">
                忘记密码？
              </Link>
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      ),
    },
    {
      key: 'phone',
      label: '手机登录',
      children: (
        <Form
          form={phoneForm}
          name="phone-login"
          onFinish={handlePhoneLogin}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input
              prefix={<MobileOutlined />}
              placeholder="请输入手机号"
            />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码为6位数字' }
            ]}
          >
            <div className="code-input-wrapper">
              <Input
                placeholder="请输入验证码"
                maxLength={6}
              />
              <Button
                onClick={handleSendCode}
                disabled={countdown > 0}
              >
                {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      ),
    },
  ];

  return (
    <div className="login-container">
      <div className="login-background">
        <div className="bg-overlay"></div>
      </div>
      
      <div className="login-content">
        <div className="login-card">
          <div className="login-header">
            <h1>欢迎回来</h1>
            <p>登录 XYQ 校园平台</p>
          </div>

          <Tabs
            activeKey={loginType}
            onChange={(key) => setLoginType(key as 'account' | 'phone')}
            items={tabItems}
            centered
          />

          <div className="login-footer">
            <span>还没有账号？</span>
            <Link to="/register" className="register-link">
              立即注册
            </Link>
          </div>

          <div className="third-party-login">
            <div className="divider">
              <span>或使用以下方式登录</span>
            </div>
            {/* 预留第三方登录按钮位置 */}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;

